package qunar;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class InheritableThreadLocalTest1 {
    public static ThreadLocal<Stu> threadLocal = new InheritableThreadLocal<>();
    public static ExecutorService executorService = Executors.newFixedThreadPool(1);

    public static void main(String[] args) throws InterruptedException {
//        System.out.println("主线程开启");
//        threadLocal.set(1);
//
//        executorService.submit(() -> {
//            System.out.println("子线程读取本地变量：" + threadLocal.get());
//            threadLocal.remove();
//        });
//
//        TimeUnit.SECONDS.sleep(1);
//
//        threadLocal.set(2);
//
//        executorService.submit(() -> {
//            System.out.println("子线程读取本地变量：" + threadLocal.get());
//            threadLocal.set(3);
//            System.out.println("子线程读取本地变量：" + threadLocal.get());
//            threadLocal.remove();
//        });

        System.out.println("主线程开启");
        threadLocal.set(new Stu("aaa",1));

        executorService.submit(() -> {
            System.out.println("子线程1读取本地变量：" + threadLocal.get());
//            threadLocal.get().setAge(55);
            System.out.println("子线程2读取本地变量：" + threadLocal.get());
        });

        TimeUnit.SECONDS.sleep(1);

        System.out.println("主线程读取本地变量：" + threadLocal.get());
        threadLocal.get().setAge(99);

        executorService.submit(() -> {
            System.out.println("子线程3读取本地变量：" + threadLocal.get());
        });

        TimeUnit.SECONDS.sleep(1);

        threadLocal.get().setAge(100);
        executorService.submit(() -> {
            System.out.println("子线程4读取本地变量：" + threadLocal.get());
        });

    }

    static class Stu{
        String name;
        int age;

        public Stu(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Stu{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}
